package com.cloud.rabbitmq.controller;

import lombok.SneakyThrows;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RabbitController {
    @Autowired(required = false)
    private AmqpTemplate amqpTemplate;

    /**
     * 简单队列模式
     *
     * @return
     */
    @RequestMapping("/rabbit/point")
    public String point() {
        String msg = "这是一个简单队列模式";
        amqpTemplate.convertAndSend("rabbit.simple.queue", msg);
        return "true";
    }

    /**
     * work模式
     *
     * @return
     */
    @SneakyThrows
    @RequestMapping("/rabbit/work")
    public void work() {
        String msg = "这是一个work模式";
        for (int i = 0; i < 10; i++) {
            amqpTemplate.convertAndSend("spring.work.queue", msg + i);
        }
        Thread.sleep(5000);
    }

    /**
     * 订阅模式
     *
     * @return
     */
    @RequestMapping("/rabbit/fanout")
    public void fanout() throws InterruptedException {
        String msg = "订阅模式";
        for (int i = 0; i < 10; i++) {
            // 这里注意细节，第二个参数需要写，否则第一个参数就变成routingKey了
            amqpTemplate.convertAndSend("spring.fanout.exchange", "", msg + i);
        }
        Thread.sleep(5000);
    }
    /**
     * 路由模式
     *
     * @return
     */
    @RequestMapping("/rabbit/direct")
    public void direct() throws InterruptedException {
        String msg = "路由模式";
        for (int i = 0; i < 10; i++) {
            amqpTemplate.convertAndSend("spring.direct.exchange", "direct", msg + i);
        }
        Thread.sleep(5000);
    }
    /**
     * 主题模式
     *
     * @return
     */
    @RequestMapping("/rabbit/topic")
    public void topic() throws InterruptedException {
        amqpTemplate.convertAndSend("spring.topic.exchange", "person.insert", "增加人员");
        amqpTemplate.convertAndSend("spring.topic.exchange", "person.delete", "删除人员");
        amqpTemplate.convertAndSend("spring.topic.exchange", "money.insert", "加钱");
        amqpTemplate.convertAndSend("spring.topic.exchange", "money.delete", "减钱");
        Thread.sleep(5000);
    }
}
